package com.example.config;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author thj
 * @date 2024-08-13
 */
@Component
public class MinioUtils {
    private final static Logger logger = LoggerFactory.getLogger(MinioUtils.class);

    @Resource
    private MinioClient minioClient;


    /**
     * 判断桶是否存在
     */
    public boolean bucketExists(String bucketName) throws Exception {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 创建桶
     * @param bucketName
     * 获取全部的桶  minioClient.listBuckets();
     */
    public void createBucket(String bucketName) throws Exception {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 根据bucketName获取信息
     * @param bucketName bucket名称
     */
    public Optional<Bucket> getBucket(String bucketName) throws Exception {
        return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
    }

    /**
     * 根据bucketName删除信息
     * @param bucketName bucket名称
     */
    public void removeBucket(String bucketName) throws Exception {
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
    }

    /**
     * 判断文件是否存在
     * @param bucketName 存储桶
     * @param objectName 文件名
     * @return
     */
    public boolean isObjectExist(String bucketName, String objectName) throws Exception {
        boolean exist = true;
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            logger.error("判断文件【{}】是否存在, 异常：", objectName, e);
            exist = false;
        }
        return exist;
    }

    /**
     * 获取文件流
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return 二进制流
     */
    public InputStream getObject(String bucketName, String objectName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 上传本地文件
     * @param bucketName 存储桶
     * @param fileName 文件名称
     * @param filePath   本地文件路径
     */
    public ObjectWriteResponse putObject(String bucketName, String fileName, String filePath) throws Exception {
        if(!bucketExists(bucketName)){
            createBucket(bucketName);
        }
        return minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucketName).object(fileName).filename(filePath).build());
    }

    /**
     * 通过流上传文件
     * @param bucketName  存储桶
     * @param objectName  文件对象
     * @param inputStream 文件流
     */
    public ObjectWriteResponse putObject(String bucketName, String objectName, InputStream inputStream) throws Exception {
        if(!bucketExists(bucketName)){
            createBucket(bucketName);
        }
        return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(inputStream, inputStream.available(), -1).build());
    }

    /**
     * 单个文件上传
     * @param bucketName
     * @param multipartFile
     * @return
     */
    public String uploadFileSingle(String bucketName, MultipartFile multipartFile ) throws Exception {
        if(!bucketExists(bucketName)){
            createBucket(bucketName);
        }
        String fileName = multipartFile.getOriginalFilename();
        String[] split = fileName.split("\\.");
        if (split.length > 1) {
            fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
        } else {
            fileName = fileName + System.currentTimeMillis();
        }
        InputStream in = null;
        try {
            in = multipartFile.getInputStream();
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
                    .stream(in, in.available(), -1).contentType(multipartFile.getContentType()).build());
        } catch (Exception e) {
            logger.error("上传文件【{}】失败!error msg:{}", fileName, e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("上传文件【{}】失败!error msg:{}", fileName, e.getMessage());
                }
            }
        }
        return getUploadObjectUrl(bucketName,fileName, 7*24*60*60);
    }

    /**
     * description: 批量上传文件
     * @param multipartFile
     * @return: java.lang.String
     */
    public List<String> uploadFileBatch(String  bucketName, MultipartFile[] multipartFile) throws Exception {
        if(!bucketExists(bucketName)){
            createBucket(bucketName);
        }
        List<String> names = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            try {
                String fileName = file.getOriginalFilename();
                uploadFileSingle(bucketName,file);
                names.add(fileName);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return names;
    }

    /**
     * 图片base64编码不存盘直接上传到minio
     * @param bucketName
     * @param imgBase64
     * @return
     * @throws Exception
     */
    public String uploadImgBase64(String bucketName, String imgBase64, String fileName) throws Exception {
        if(!bucketExists(bucketName)){
            createBucket(bucketName);
        }
        // 去掉base64前缀 data:image/jpeg;base64,
        imgBase64 = imgBase64.substring(imgBase64.indexOf(",", 1) + 1, imgBase64.length());
        // 解密
        byte[] decode = Base64.getDecoder().decode(imgBase64);
        InputStream byteArrayInputStream = new ByteArrayInputStream(decode);
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
                .stream(byteArrayInputStream, byteArrayInputStream.available(), -1)
                .contentType("image/jpeg").build());
        return getUploadObjectUrl(bucketName, fileName, 7*24*60*60);
    }

    /**
     * 获取文件外链
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @param expires    过期时间 <=7 秒级
     * @return url
     */
    public String getUploadObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
        if(!isObjectExist(bucketName, objectName)){
            return "";
        }
        String fileUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.PUT).bucket(bucketName)
                .object(objectName).expiry(expires).build());
        return fileUrl.substring(0, fileUrl.indexOf("?"));
    }

    /**
     * 下载文件
     * @param bucketName:桶名
     * @param fileName: 文件名
     */
    public void download(String bucketName, String fileName, HttpServletResponse response) throws Exception {
        // 获取对象的元数据
        StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
        response.setContentType(stat.contentType());
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream is = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
        IOUtils.copy(is, response.getOutputStream());
        is.close();
    }

    /**
     * 删除文件
     * @param bucketName ：bucket名称
     * @param fileName: 删除的文件名称
     */
    public boolean removeObject(String bucketName, String fileName) {
        try{
            if (!isObjectExist(bucketName, fileName)) {
                return true;
            }
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        }catch (Exception e) {
            logger.error("删除文件【{}】异常!", fileName, e);
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket下的所有文件
     * @param bucketName ：bucket名称
     */
    public void removeObjects(String bucketName) throws Exception {
        // 获取存储bucket下的所有文件
        Iterable<Result<Item>> list = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        // 转换为DeleteObject列表
        List<DeleteObject> deleteObjects = new LinkedList<>();
        list.forEach(itemResult -> {
            try {
                deleteObjects.add(new DeleteObject(itemResult.get().objectName()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(deleteObjects).build());
        for(Result<DeleteError> result : results){
            if(result.get() != null){
                logger.info("删除文件失败：{}", result.get().toString());
            }
        }
        /*results.forEach(result -> {
            try {
                logger.info("删除文件失败：{}", result.get().toString());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });*/
    }

}
